package com.shujia.hw2;

import redis.clients.jedis.Jedis;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Properties;

public class Server {
    public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, InterruptedException {
        Jedis jedisCon = new Jedis("master", 6379);

        // 创建Mysql连接
        Class.forName("com.mysql.jdbc.Driver");
        Properties properties = new Properties();
        properties.load(new FileReader("redisCode/src/main/resources/mysql.properties"));
        String url = properties.getProperty("url");
        String user = properties.getProperty("user");
        String passwd = properties.getProperty("passwd");
        Connection connection = DriverManager.getConnection(url, user, passwd);



        while (true){
            Thread.sleep(1000);

            // 不断询问Redis中 key 为sql的value有没有数据
            String sql = jedisCon.get("sql");

            if (sql!=null){
                System.out.println("获取到sql:"+sql);
                // 不为null,那么需要获取sql并执行
                Statement statement = connection.createStatement();
                ResultSet resultSet = statement.executeQuery(sql);

                // 获取结果数据的元数据
                ResultSetMetaData metaData = resultSet.getMetaData();
                int columnCount = metaData.getColumnCount();

                ArrayList<String> allDataList = new ArrayList<>();

                String[] oneLineValue = new String[columnCount];
                while (resultSet.next()){
                    // 这时，可以获取到结果中的一行数据
                    for (int i = 1; i <= columnCount; i++) {
                        // 一行中单个列的数据
                        String colValue = resultSet.getString(i);// 列的下标从1开始
                        oneLineValue[i-1] = colValue;
                    }
                    allDataList.add(Arrays.toString(oneLineValue));
                }

                for (String oneData : allDataList) {
                    // 一个SQL语句需要又一个Key,并且客户端也能够直到Key的值是多少
                    jedisCon.lpush(String.valueOf(sql.hashCode()),oneData);
                }

                // 数据返回后 将SQL语句删除
                jedisCon.del("sql");

            }
        }
    }
}
